package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.*;
import com.lzx.iteam.bean.aidl.EventReplyNewData;
import com.lzx.iteam.bean.aidl.ActiveDetailBean;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.provider.EventsMsgDB;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangshuai on 15-5-27.
 */
public class MyMessage {

    public static class SendReplyMessage extends CcMsgStructure {

        private Message mmCallback;
        private EventsMsgDB mMsgDB;

        public SendReplyMessage(Message mmCallback, Context mContext) {
            this.mmCallback = mmCallback;
            mMsgDB = new EventsMsgDB(mContext);
        }

        @Override
        public void onReceive(JSONObject data) {

            final EventReplyNewData result = new EventReplyNewData();
            try {
                JSONObject object = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
                result.setEventId(object.getString("event_id"));
                result.setUserId(object.getString("user_id"));
                result.setUserName(object.getString("user_name"));
                result.setContent(object.getString("content"));
                result.setUpdateTime(object.getString("update_time"));
                result.setAvatar(object.getString("user_image"));
                if (object.has("attachment")) {
                    result.setAttachments(object.getJSONArray("attachment").toString());
                }
                result.setIsReaded(true);
                mMsgDB.insertEventReply(result);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (mmCallback != null) {
                mmCallback.arg1 = 0;
                mmCallback.obj = result;
                mmCallback.sendToTarget();
            }
        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    public static class GetReplyMessage extends CcMsgStructure {

        private Message mmCallback;
        private EventsMsgDB mMsgDB;
        private String mEventId;
        private String mEventType;
        private int mCount;
        private int mVoteMember = -1;

        public GetReplyMessage(Message mmCallback, EventsMsgDB mMsgDB, String mEventId, String mEventType) {
            this.mmCallback = mmCallback;
            this.mMsgDB = mMsgDB;
            this.mEventId = mEventId;
            this.mEventType = mEventType;
        }

        public GetReplyMessage(Message mmCallback, EventsMsgDB mMsgDB, String mEventId, String mEventType, int count) {
            this.mmCallback = mmCallback;
            this.mMsgDB = mMsgDB;
            this.mEventId = mEventId;
            this.mEventType = mEventType;
            this.mCount = count;
        }

        @Override
        public void onReceive(JSONObject data) {
            ArrayList<EventReplyNewData> list = new ArrayList<EventReplyNewData>();
            ArrayList<EventVoteBean> voteList = new ArrayList<EventVoteBean>();
            try {

                if (mEventType.equals("7")) {
                    JSONObject object = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
                    EventReplyNewData eventReplyNewData = new EventReplyNewData();
                    eventReplyNewData.setMemberCount(object.getString("member_count"));
                    eventReplyNewData.setJoinCount(object.getString("join_count"));
                    JSONArray detail = object.getJSONArray("join_members");
                    ArrayList<ActiveDetailBean> detailBeans = new ArrayList<ActiveDetailBean>();
                    for (int i = 0; i < detail.length(); i++) {
                        JSONObject object1 = detail.getJSONObject(i);
                        ActiveDetailBean bean = new ActiveDetailBean();
                        bean.setImage(object1.getString("user_image"));
                        bean.setName(object1.getString("user_name"));
                        bean.setPhone(object1.getString("user_phone"));
                        bean.setUid(object1.getString("user_id"));
                        detailBeans.add(bean);
                    }
                    eventReplyNewData.setActiveDetailBeans(detailBeans);
                    list.add(eventReplyNewData);
                } else if (mEventType.equals("8")) {

                    JSONObject object = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
                    for (int i = 0; i < mCount; i++) {
                        EventVoteBean bean = new EventVoteBean();
                        //bean.setVote((char)(65 + i) + "");
                        bean.setCount(object.getInt((char) (65 + i) + ""));
                        voteList.add(bean);
                    }
                    if (object.has("vote_member")){
                        mVoteMember = object.getInt("vote_member");
                    }

                } else if (mEventType.equals("9")) {

                } else {

                    JSONArray array = data.getJSONArray(AsynHttpClient.KEY_CC_DATA);
                    int r = mMsgDB.deleteMessagesByEventID(mEventId);
                    Log.i("delete_data", "删除" + r);
                    for (int i = 0; i < array.length(); i++) {
                        final EventReplyNewData eventReplyNewData = new EventReplyNewData();
                        JSONObject object = array.getJSONObject(i);
                        eventReplyNewData.setUserName(object.getString("user_name"));
                        eventReplyNewData.setUpdateTime(object.getString("create_time"));
                        eventReplyNewData.setContent(object.getString("content"));
                        eventReplyNewData.setUserId(object.getString("user_id"));
                        eventReplyNewData.setAvatar(object.getString("user_image"));
                        if (object.has("event_id")) {
                            eventReplyNewData.setEventId(object.getString("event_id"));
                        }
                        if (object.has("attachment")) {
                            eventReplyNewData.setAttachments(object.getJSONArray("attachment").toString());
                        }
                        eventReplyNewData.setIsReaded(true);
                        list.add(eventReplyNewData);
                        mMsgDB.insertEventReply(eventReplyNewData);


                    }
                }
            } catch (JSONException e) {
                Log.e("get_reply_error", e.toString());
                e.printStackTrace();
            }
            if (mmCallback != null) {
                if (mEventType.equals("8")) {
                    mmCallback.obj = voteList;
                    mmCallback.arg2 = mVoteMember;
                } else if (mEventType.equals("9")) {
                    mmCallback.obj = data;
                } else {
                    mmCallback.obj = list;
                }
                mmCallback.arg1 = 0;
                mmCallback.sendToTarget();
            }

        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }


    public static class GetNewEventListMessage extends CcMsgStructure {

        private Message mmCallback;
        private CloudDBOperation cloudDBOperation;
        private EventsMsgDB mMsgDB;
        private Context mContext;
        private String type;

        public GetNewEventListMessage(Message mCallback, Context mContext, String type) {
            this.mmCallback = mCallback;
            this.mContext = mContext;
            this.type = type;
            cloudDBOperation = new CloudDBOperation(mContext);
            mMsgDB = new EventsMsgDB(mContext);
        }

        @Override
        public void onReceive(JSONObject data) {
            final ArrayList<EventListData> list = new ArrayList<EventListData>();
            try {
                JSONArray item = data.getJSONArray(AsynHttpClient.KEY_CC_DATA);
                for (int i = 0; i < item.length(); i++) {
                    JSONObject object = item.getJSONObject(i);
                    final EventListData listData = new EventListData();
//                    listData.setUpdateTime(object.getString("update_time"));
                    //listData.setCreateTime(object.getString("create_time"));
                    listData.setUserType(object.getString("user_type"));
                    listData.setHasRead(object.getString("has_read"));
                    if (object.has("has_join")) {
                        listData.setHasJoin(object.getString("has_join"));
                    }
                    if (object.has("_id")) {
                        listData.setId(object.getString("_id"));
                    }
                    if (object.has("reply") && object.getJSONObject("reply").length() > 0) {
                        JSONObject reply = object.getJSONObject("reply");
                        listData.setReplyLastName(reply.getString("uname"));
                        listData.setReplyLastContent(reply.getString("reply"));
                    }
                    JSONObject event = object.getJSONObject("event");
                    listData.setUpdateTime(event.getString("update_time"));
                    listData.setEventType(event.getString("event_type"));
                    listData.setEventId(event.getString("_id"));
                    listData.setUserId(event.getString("user_id"));
                    listData.setUserName(event.getString("user_name"));
                    if (event.has("user_img")) {
                        listData.setEventAvatar(event.getString("user_img"));
                    }
                    if (event.has("create_time")) {
                        String createTime = event.getInt("create_time") + "";
                        if (createTime.contains(".")) {
                            createTime = createTime.substring(0, createTime.length() - 3);
                        }
                        listData.setCreateTime(createTime);
                    }
                    listData.setMemberCount(event.getString("member_count"));
                    listData.setEventTitle(event.getString("event_title"));
                    if (event.has("has_read_count")) {
                        listData.setHasReadCount(event.getString("has_read_count"));
                    }
                    if (event.has("reply_count")) {
                        listData.setReplyCount(event.getString("reply_count"));
                    }
                    if (event.has("author")) {
                        listData.setAuthor(event.getString("author"));
                    }
                    if (event.has("attachment")) {
                        JSONArray image = event.getJSONArray("attachment");
                        StringBuilder thumbSb = new StringBuilder();
                        StringBuilder oriSb = new StringBuilder();
                        for (int k = 0; k < image.length(); k++) {
                            JSONObject imageObject = image.getJSONObject(k);
//                            if(imageObject.getString("type").equals("1"))
                            if (imageObject.has("thumb")) {
                                thumbSb.append(imageObject.getString("thumb") + ",");
                            }
                            if (imageObject.has("ori")) {
                                oriSb.append(imageObject.getString("ori") + ",");
                            }
                        }
                        if (thumbSb.length() > 0) {
                            listData.setThumbImage(thumbSb.substring(0, thumbSb.length() - 1));
                        }
                        if (oriSb.length() > 0) {
                            listData.setOriImage(oriSb.substring(0, oriSb.length() - 1));
                        }
                    }
                    if (event.has("join_count")) {
                        listData.setJoinCount(event.getString("join_count"));
                    }
                    if (event.has("event_address")) {
                        listData.setActivitySite(event.getString("event_address"));
                    }
                    if (event.has("event_date")) {
                        listData.setActivityTime(event.getString("event_date"));
                    }
                    if (event.has("event_time")) {
                        listData.setActivityTime(event.getString("event_time"));
                    }
                    if (event.has("qrcode")) {
                        listData.setQrcode(event.getString("qrcode"));
                    }
                    if (event.has("event_templ_name")) {
                        listData.setEventName(event.getString("event_templ_name"));
                    } else {
                        listData.setEventName("");
                    }

                    final int count = mMsgDB.getUnReadCountOfOneEvent(event.getString("_id"));
                    listData.setUnReadCount(count + "");
                    if (event.getString("event_type").equals("7") || event.getString("event_type").equals("9")) {
                        listData.setContent1(event.getString("event_content"));
                    } else if (event.getString("event_type").equals("8")) {
                        StringBuilder votes = new StringBuilder();
                        JSONArray array = new JSONArray(event.getString("event_content"));
                        for (int j = 0; j < array.length(); j++) {
                            String vote = array.getJSONObject(j).getString("content");
                            votes.append(vote).append(",");
                        }
                        listData.setContent1(votes.toString());
                    } else {
                        JSONArray content = event.getJSONArray("event_content");
                        switch (content.length()) {
                            case 3:
                                if (content.getJSONObject(2).has("content")) {
                                    listData.setContent3(content.getJSONObject(2).getString("content"));
                                }
                                if (content.getJSONObject(2).has("init_title")) {
                                    listData.setInitTitle3(content.getJSONObject(2).getString("init_title"));
                                }
                                if (content.getJSONObject(2).has("url")) {
                                    listData.setUrl3(content.getJSONObject(2).getString("url"));
                                }
                            case 2:
                                if (content.getJSONObject(1).has("content")) {
                                    listData.setContent2(content.getJSONObject(1).getString("content"));
                                }
                                if (content.getJSONObject(1).has("init_title")) {
                                    listData.setInitTitle2(content.getJSONObject(1).getString("init_title"));
                                }
                                if (content.getJSONObject(1).has("url")) {
                                    listData.setUrl2(content.getJSONObject(1).getString("url"));
                                }

                            case 1:
                                if (content.getJSONObject(0).has("content")) {
                                    listData.setContent1(content.getJSONObject(0).getString("content"));
                                }
                                if (content.getJSONObject(0).has("init_title")) {
                                    listData.setInitTitle1(content.getJSONObject(0).getString("init_title"));
                                }
                                if (content.getJSONObject(0).has("url")) {
                                    listData.setUrl1(content.getJSONObject(0).getString("url"));
                                }

                                break;
                        }
                    }
                    list.add(listData);
                    if ("0".equals(type) || "-1".equals(type)) {
                        long l = cloudDBOperation.insertEvent(listData);
                        Log.i("EventList", "--添加result--" + l);
                    }
                }

            } catch (JSONException e) {
                Log.e("new_event", e.toString());
                e.printStackTrace();
            }

            if (mmCallback != null) {
                mmCallback.obj = list;
                mmCallback.arg1 = 0;
                mmCallback.sendToTarget();
            }

        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }


    public static class GetCustomModelMessage extends CcMsgStructure {

        private Message mmCallback;
        private PreferenceUtil mPreferenceUtil;
        private Context mContext;

        public GetCustomModelMessage(Message mmCallback, Context mContext) {
            this.mmCallback = mmCallback;
            this.mContext = mContext;
            mPreferenceUtil = PreferenceUtil.getInstance(mContext);

        }

        @Override
        public void onReceive(JSONObject data) {

            List<EventListData> mList = new ArrayList<EventListData>();
            try {
                JSONArray array = data.getJSONArray(AsynHttpClient.KEY_CC_DATA);
                mPreferenceUtil.save(PreferenceUtil.CUSTOM_EVENT, array.toString());
                for (int i = 0; i < array.length(); i++) {
                    EventListData model = new EventListData();
                    JSONObject object = array.getJSONObject(i);
                    // model.setUpdateTime(object.getString("update_time"));
                    model.setUserId(object.getString("user_id"));
                    model.setEventName(object.getString("event_temp_name"));
                    model.setEventTitle(object.getString("event_title"));
                    model.setReceiver(object.getJSONArray("init_recv_uids").toString());
                    model.setEventId(object.getString("_id"));
                    JSONArray contents = object.getJSONArray("event_contents");
                    if (contents.length() == 3) {
                        model.setInitTitle1(contents.getJSONObject(0).getString("init_title"));
                        model.setInitTitle2(contents.getJSONObject(1).getString("init_title"));
                        model.setInitTitle3(contents.getJSONObject(2).getString("init_title"));
                    } else if (contents.length() == 2) {
                        model.setInitTitle1(contents.getJSONObject(0).getString("init_title"));
                        model.setInitTitle2(contents.getJSONObject(1).getString("init_title"));
                    } else if (contents.length() == 1) {
                        model.setInitTitle1(contents.getJSONObject(0).getString("init_title"));
                    }
                    mList.add(model);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (mmCallback != null) {
                mmCallback.obj = mList;
                mmCallback.arg1 = 0;
                mmCallback.sendToTarget();
            }

        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    public static class DeleteCustomModelMessage extends CcMsgStructure {

        private Message mmCallback;

        public DeleteCustomModelMessage(Message mmCallback) {
            this.mmCallback = mmCallback;
        }

        @Override
        public void onReceive(JSONObject data) {

            if (mmCallback != null) {
                mmCallback.arg1 = 0;
                mmCallback.sendToTarget();
            }
        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    public static class MakeCustomModelMessage extends CcMsgStructure {

        private Message mmCallback;

        public MakeCustomModelMessage(Message mmCallback) {
            this.mmCallback = mmCallback;
        }

        @Override
        public void onReceive(JSONObject data) {
            JSONObject object = null;
            try {
                object = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (mmCallback != null) {
                mmCallback.arg1 = 0;
                mmCallback.obj = object;
                mmCallback.sendToTarget();
            }

        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    public static class EventRegMessage extends CcMsgStructure {

        private Message mmCallback;

        public EventRegMessage(Message mmCallback) {
            this.mmCallback = mmCallback;
        }

        @Override
        public void onReceive(JSONObject data) {
            JSONObject object = null;
            try {
                object = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (mmCallback != null) {
                mmCallback.arg1 = 0;
                mmCallback.obj = object;
                mmCallback.sendToTarget();
            }

        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

}
